/*
 Copyright (c) Whitemice Consulting, 2007, 2008, 2009
 Adam Tauno Williams <awilliam@whitemice.org>
 License: MIT/X11

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

using System;
using System.Linq;
using System.Collections;
using System.Threading;
using System.Collections.Generic;
using Whitemice.ZOGI.Backend;

namespace Whitemice.ZOGI
{
  public partial class Server
  {   
    //private   IDictionary<int,List<WeakReference>>  subscribers;
    public    static Server                         Connection;
    protected static Cache                          cache;
    internal WorkQueue                              workQueue;
    protected Thread                                workThread;
    protected UserProfile                           profile;
        
    public Server()
    {
      //subscribers = new Dictionary<int,List<WeakReference>>(512);
      cache = new Cache();
      profile = new UserProfile();
      workQueue = new WorkQueue();
      workThread = new Thread(new ThreadStart(WorkThread));
      workThread.Name = "Background Work Thread#1";
      workThread.IsBackground = true;
      workThread.Start();
    } // end ctor
    
    public static void Initialize()
    {
      Connection = new Server(); 
    }
    
    protected void WorkThread()
    {
      while (true)
      {
          object z = workQueue.Dequeue();
          if (z is IAsyncResult)
            ProcessResult(z as IAsyncResult);
          else if (z is IZOGICommand)
            Issue(z as IZOGICommand);
      }
    } // end WorkThread
    
    public static Cache Cache { get { return cache; } }

    public UserProfile UserProfile { get { return profile; } }
    
    public void	Connect(string hostName, int port, 
                        string userName, string password)
    {
      client = null;
      this.Establish(hostName, port, userName, password);
    } // end Connect
    
    public bool Connected { get { return (client != null); } }

    public void RunCommand(IZOGICommand command)
    {
      RunCommand(command, RpcPriority.Application);
    } // end RunCommand
    
    public void	RunCommand(IZOGICommand command, RpcPriority priority)
    {
      if (command.Callback == null)
        this.ZLOG("Command {0} queued with NULL callback", command.Id);
      if (Connected)
        RunOnlineCommand(command, priority);
        else RunOfflineCommand(command);
    } // end RunCommand

    protected bool SaitFetch(IZOGIFetchCommand c)
    {
      Whitemice.ZOGI.Entity         e;

      lock(Server.Cache)
      {
        try
        {
          foreach(int objectId in c.ObjectIds)
            if (Server.Cache.Has(objectId, c.DetailLevel, out e))
              if (!(c.Cache.Contains(e)))
                c.Cache.Add(e);
        } catch(Exception exception)
          {
            Console.WriteLine("Exception in SaitFetch: {0}", exception.Message);
            Console.WriteLine("Source: {0}", exception.Source);
            Console.WriteLine(exception.StackTrace);
            return false;
          }
      }
      if (c.IsSaited)
      {
        this.ZLOG("Sait calling back.");
        if (c.Callback != null)
          c.Callback(this,
                     new RPCEventArgs(c.Id, c.Cache, c.Context, null));
        return true;
      }
      return false;
    } // end SaitFetch
    
    protected void RunOnlineCommand(IZOGICommand command, RpcPriority priority)
    {
      this.ZLOG(string.Format("Server received {0} at {1} priority.", command, priority));
      if (command is IZOGISearchCommand)
      {
        workQueue.Enqueue(command, priority);
        return;
      } // end if-is-search-command
      
      if (command is IZOGIFetchCommand)
      {
        // If the fetch can be saited from the fetch we return immediately
        if ((command as IZOGIFetchCommand).UseCache)
        {
          if (SaitFetch(command as IZOGIFetchCommand))
          {
            this.ZLOG("Fetch saited from cache (early)");
            return;
          }
        }
        workQueue.Enqueue(command, priority);
        return;
      } // end if-is-fetch-command
      
      if (command is IZOGIPutCommand)
      {
        workQueue.Enqueue(command, RpcPriority.Immediate);
        return;
      }
      
      if (command is IZOGIDeleteCommand)
      {
        workQueue.Enqueue(command, RpcPriority.Immediate);
        return;
      }
      
      throw new Exception("Unhandled command in RunCommand");
    } // end RunOnlineCommand
    
    protected void RunOfflineCommand(IZOGICommand command)
    {
      if (command is IZOGISearchCommand)
      {
        return;
      } // end if-is-search-command
      
      if (command is IZOGIFetchCommand)
      {
        IList<Whitemice.ZOGI.Entity>  x;
        IZOGIFetchCommand             c;
        Whitemice.ZOGI.Entity         e;
        Whitemice.ZOGI.Backend.Cache  z;
        
        z = Server.Cache;
        c = (command as IZOGIFetchCommand);
        x = new List<Whitemice.ZOGI.Entity>();
        foreach(int objectId in c.ObjectIds)
          if (z.Has(objectId, c.DetailLevel, out e))
            x.Add(e);
        if (c.Callback != null)
          c.Callback(this,
                     new RPCEventArgs(c.Id,
                                      c.Cache, 
                                      c.Context, 
                                      null));
      } // end if-is-fetch-command
    } // end RunOfflineCommand
    
    public void	Disconnect()
    {
      client = null;
    }

    public bool WorkQueueStatus(out int count)
    {
      lock(this.workQueue)
      {
        count = workQueue.Count;
      }
      return workQueue.IsBusy;
    }
    
    private static int internalId = -1;
    internal static int InternalId { get { return internalId--; } }

    public ZOGIExceptionHandler			      OnException;
    public ZOGIUserMessageHandler		    	OnUserMessage;
    public ZOGIPluginDataHandler		    	OnReceivedPluginData;
    //public zOGIAppointmentReminderHandler	OnReminderEvent;
    public EventHandler					          OnConnected;
    public EventHandler					          OnDisconnect;
  }
}